<?php
namespace Seller\Controller;
use Seller\Logic\GoodsLogic;
use Seller\Logic\OrderLogic;
// use WXAPI\Controller\PintController;
use Think\AjaxPage;
use Think\Page;

class PintController extends BaseController {

    /**
     *  商品列表
     */
    public function goodsList(){
        
        // checkIsBack();
        $store_goods_class_list = M('store_goods_class')->where("parent_id = 0 and store_id = ".STORE_ID)->select();
        $this->assign('store_goods_class_list',$store_goods_class_list);        
        $this->display();                                           
    }
    
    /**
     *  商品列表
     */
    public function ajaxGoodsList(){         
 
        $where = "store_id = ".STORE_ID; // 搜索条件
        $intro = I("intro");
        (I('store_cat_id1') !== '') && $where = "$where and store_cat_id1 = ".I('store_cat_id1');
        (I('is_on_sale') !== '') && $where = "$where and is_on_sale = ".I('is_on_sale');
        $goods_state = I('goods_state'); // 商品状态  0待审核 1审核通过 2审核失败  3违规下架        
        $goods_state && $where = "$where and goods_state in ($goods_state) ";
        
        // 关键词搜索               
        $key_word = I('key_word') ? trim(I('key_word')) : '';
        if($key_word)
        {
            $where = "$where and (goods_name like '%$key_word%' or goods_sn like '%$key_word%')" ;
        }
        if($intro == 'pt_hot'){
            $where .= " and pt_hot = 1 ";
        }elseif($intro == 'pt_hot_not'){
            $where .= " and pt_hot = 0 ";
        }

        $where .= " and is_pint = 1 ";
        $model = M('Goods');
        $count = $model->where($where)->count();
        $Page  = new AjaxPage($count,10);
        
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        
        //是否从缓存中获取Page
        if(session('is_back')==1){
            $Page = getPageFromCache();
            //重置获取条件
            delIsBack();
        }
        
        $goodsList = $model->where($where)->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();
 
        cachePage($Page);
        $show = $Page->show();
        
        $catList = D('goods_category')->select();
        $catList = convert_arr_key($catList, 'id');
        $this->assign('catList',$catList);
        $this->assign('goodsList',$goodsList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();         
    }    
    
    
   /**
     * 添加修改商品
     */
    public function addEditGoods(){   
            
            $GoodsLogic = new GoodsLogic();                         
            $Goods = D('Admin/Goods'); //
            $goods_id = I('goods_id',0);
            $type = $goods_id > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新                        
            //
            if($goods_id > 0)
            {
                $c = M('goods')->where("goods_id = $goods_id and store_id = ".STORE_ID)->count();
                if($c == 0)  
                    $this->error("非法操作",U('Pint/goodsList'));
            }
                        
            //
            //ajax提交验证
            if(($_GET['is_ajax'] == 1) && IS_POST)
            {                
                
                C('TOKEN_ON',false);
                if(!$Goods->create(NULL,$type))// 根据表单提交的POST数据创建数据对象                 
                {
                    //  编辑
                    $error = $Goods->getError();
                    $error_msg = array_values($error);
                    $return_arr = array(
                        'status' => -1,
                        'msg' => $error_msg[0],
                        'data' => $error,
                    );
                    $this->ajaxReturn(json_encode($return_arr));
                }else {
                   // form表单提交
                   // C('TOKEN_ON',true);                                                            
                    $Goods->on_time = time(); // 上架时间
                    $cat_id3 = I('cat_id3',0);
                    $_POST['extend_cat_id_2'] && ($Goods->extend_cat_id = I('extend_cat_id_2'));
                    $_POST['extend_cat_id_3'] && ($Goods->extend_cat_id = I('extend_cat_id_3'));
                    $Goods->shipping_area_ids = implode(',',$_POST['shipping_area_ids']);
                    $Goods->shipping_area_ids = $Goods->shipping_area_ids ? $Goods->shipping_area_ids : '';
                    
                    $type_id = M('goods_category')->where("id = $cat_id3")->getField('type_id'); // 找到这个分类对应的type_id
                    $store_goods_examine = M('store')->where(array('store_id'=>STORE_ID))->getField('goods_examine');
                    $Goods->goods_type = $type_id ? $type_id : 0;
                    $Goods->store_id = STORE_ID; // 店家id
                    if($store_goods_examine){
                        $Goods->goods_state = 0; // 待审核
                    }else{
                        $Goods->goods_state = 1; // 出售中
                    }
                    $Goods->is_pint = 1;
                    
                    if($Goods->distribut > ($Goods->shop_price / 2))
                        $this->ajaxReturn(json_encode(array('status' => -1,'msg'=> '分销的分成金额不得超过商品金额的50%','data'  =>'')));
                    if ($type == 2)
                    {    
                        if(M('Goods')->where(array('goods_id'=>$goods_id,'store_id'=>STORE_ID))->count()>0){
                            // 修改商品后购物车的商品价格也修改一下
                            M('cart')->where("goods_id = $goods_id and spec_key = ''")->save(array(
                                    'market_price'=>$_POST['market_price'], //市场价
                                    'goods_price'=>$_POST['shop_price'], // 本店价
                                    'member_goods_price'=>$_POST['shop_price'], // 会员折扣价                        
                                    ));                            
                            $Goods->save(); // 编辑数据到数据库
                        }else{
                            $this->ajaxReturn(array('status' => -1,'msg'=> '非法操作'),'JSON');
                        }                                                                                             
                    }
                    else
                    {                           
                        $goods_id = $Goods->add(); // 新增数据到数据库                        
                    }                                        
                 
                    $Goods->afterSave($goods_id,STORE_ID);                                        
                    $GoodsLogic->saveGoodsAttr($goods_id,$type_id,STORE_ID); // 处理商品 属性
                    
                    $return_arr = array(
                        'status' => 1,
                        'msg'   => '操作成功',                        
                        'data'  => array('url'=>U('Pint/goodsList')),
                    );
                   //重定向, 调整之前URL是设置参数获取方式 
                   session("is_back" , 1);
                   $this->ajaxReturn(json_encode($return_arr));
                }  
            }else{
                
            }
            
            $goodsInfo =M('Goods')->where('goods_id='.I('GET.goods_id',0))->find();  
            $store = M('store')->where(array('store_id'=>STORE_ID))->find();
            
            $cat_list = M('goods_category')->where("parent_id = 0")->select();//自营店已绑定所有分类
                                 
            $store_goods_class_list = M('store_goods_class')->where("parent_id = 0 and store_id = ".STORE_ID)->select(); //店铺内部分类                      
            $brandList = $GoodsLogic->getSortBrands();
            $goodsType = M("GoodsType")->select();
            $suppliersList = M("suppliers")->select();
            $plugin_shipping = M('plugin')->where(array('type'=>array('eq','shipping')))->select();//插件物流
            $shipping_area = D('shipping_area')->getShippingArea(STORE_ID);//配送区域
            $goods_shipping_area_ids = explode(',',$goodsInfo['shipping_area_ids']);
            $this->assign('goods_shipping_area_ids',$goods_shipping_area_ids);
            $this->assign('shipping_area',$shipping_area);
            $this->assign('plugin_shipping',$plugin_shipping);
            $this->assign('cat_list',$cat_list);
            $this->assign('store_goods_class_list',$store_goods_class_list);
            $this->assign('brandList',$brandList);
            $this->assign('goodsType',$goodsType);
            $this->assign('suppliersList',$suppliersList);
            $this->assign('goodsInfo',$goodsInfo);  // 商品详情            
            $goodsImages = M("GoodsImages")->where('goods_id ='.I('GET.goods_id',0))->select();
            $this->assign('goodsImages',$goodsImages);  // 商品相册
            $this->initEditor(); // 编辑器
            $this->display('_goods');                                     
    }


    /**
     * 初始化编辑器链接     
     * 本编辑器参考 地址 http://fex.baidu.com/ueditor/
     */
    private function initEditor()
    {
        $this->assign("URL_upload", U('Admin/Ueditor/imageUp',array('savepath'=>'goods'))); // 图片上传目录
        $this->assign("URL_imageUp", U('Admin/Ueditor/imageUp',array('savepath'=>'article'))); //  不知道啥图片
        $this->assign("URL_fileUp", U('Admin/Ueditor/fileUp',array('savepath'=>'article'))); // 文件上传s
        $this->assign("URL_scrawlUp", U('Admin/Ueditor/scrawlUp',array('savepath'=>'article')));  //  图片流
        $this->assign("URL_getRemoteImage", U('Admin/Ueditor/getRemoteImage',array('savepath'=>'article'))); // 远程图片管理
        $this->assign("URL_imageManager", U('Admin/Ueditor/imageManager',array('savepath'=>'article'))); // 图片管理        
        $this->assign("URL_getMovie", U('Admin/Ueditor/getMovie',array('savepath'=>'article'))); // 视频上传
        $this->assign("URL_Home", "");
    }

    private function getGoodsInfoForPt()
    {
        $goods_id = I('goods_id',0);
        $goods = M("goods")->where(array("store_id"=>STORE_ID,"goods_id"=>$goods_id))->find();
        if(!$goods){
            $return_arr = array('status' => 0,'msg'=> '找不到该商品!');
            exit(json_encode($return_arr));
        }
        if($goods['is_pint'] == 1){
            $return_arr = array('status' => 2,'msg'=> '该商品已经是拼团商品!');
            exit(json_encode($return_arr));
        }
        if($goods['is_on_sale'] != 1){
            $return_arr = array('status' => 3,'msg'=> '该商品非上架商品!');
            exit(json_encode($return_arr));
        }
        if($goods['goods_state'] != 1){
            $return_arr = array('status' => 4,'msg'=> '该商品未通过审核!');
            exit(json_encode($return_arr));
        }
        $return_arr = array('status' => 1,'msg'=> '查找成功!','data' => $goods);
        exit(json_encode($return_arr));
    }

    //拼团列表
    public function pintList(){
        $this->display();
    }
    
    /**
     *  拼团列表
     */
    public function ajaxPintList(){
        $wxapi = new \WXAPI\Controller\PintController;
        $wxapi->pint_check_order();
        $where = "store_id = ".STORE_ID; // 搜索条件

        $pint_status = I('pint_status');
        if($pint_status != 3){
            $where = "$where and pint_status ='$pint_status'" ;
        }

        // 会员id搜索       
        $user_id = I('user_id') ? trim(I('user_id')) : '0';

        if($user_id)
        {
            $where = "$where and user_id ='$user_id'" ;
        }

        // 商品id搜索               
        $goods_id = I('goods_id') ? trim(I('goods_id')) : '0';
        if($goods_id)
        {
            $where = "$where and goods_id ='$goods_id'" ;
        }
        

        $model = M('Pint');
        $count = $model->where($where)->count();

        // var_dump($where);die;
        // var_dump($count);
        $Page  = new AjaxPage($count,10);
        
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        
        // 是否从缓存中获取Page
        if(session('is_back')==1){
            $Page = getPageFromCache();
            //重置获取条件
            delIsBack();
        }
        
        $pintList = $model->where($where)->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();
        $pintList = $model->where($where)->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();
        if($pintList){
            $g = array();
            $u = array();
            foreach($pintList as $v){
                $g[] = $v['goods_id'];
                $u[] = $v['user_id'];
            }
            $u = implode(',',array_unique($u));
            $g = implode(',',array_unique($g));
            $goods = M()->query("select goods_id,goods_name from ty_goods where goods_id in (".$g.")");
            $users = M()->query("select user_id,nickname from ty_users where user_id in (".$u.")");

            $g = array();
            $u = array();
            foreach($goods as $v){
                $g[$v['goods_id']] = $v['goods_name'];
            }
            foreach($users as $v){
                $u[$v['user_id']] = $v['nickname'];
            }
            $this->assign('g',$g);
            $this->assign('u',$u);
        }

        cachePage($Page);
        $show = $Page->show();
        
        $this->assign('stus',array(0=>'拼团中',1=>'拼团成功',2=>'拼团失败'));
        $this->assign('pintList',$pintList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display('ajaxPintList');
    }


    /**
     * 查看拼团详情
     */
   public function pintInfo(){

        $pint_id = I('pint_id');
        $pint = M('pint')->find($pint_id);
        if(!$pint){
            echo '找不到该拼团信息';
            die;
        }
        $u = M('users');
        $o = M('order');
        $goods = M('goods')->find($pint['goods_id']);
        $users['tuanzhang_id'] = $pint['user_id'];
        $users = M('order')->where(array('order_prom_type'=>'101','order_prom_id'=>$pint_id))->where("!(pay_code!='cod' and pay_status=0)")->select();
        $goods = M('goods')->find($pint['goods_id']);
        $this->assign('pint',$pint);
        $this->assign('goods',$goods);
        $this->assign('users',$users);
        $this->assign('pint_stus',array(0=>'进行中',1=>'拼团成功',2=>'拼团失败'));
        $order_status = C('ORDER_STATUS');
        $pay_status = C('PAY_STATUS');
        $shipping_status = C('SHIPPING_STATUS');
        $this->assign('order_status',$order_status);
        $this->assign('pay_status',$pay_status);
        $this->assign('shipping_status',$shipping_status);
        $this->display();
    }


    /*
     *订单首页
     */
    public function pintOrder(){
        $begin = date('Y/m/d',(time()-30*60*60*24));//30天前
        $end = date('Y/m/d',strtotime('+1 days'));  
        $this->assign('timegap',$begin.'-'.$end);

        $this->assign('order_status',C('ORDER_STATUS'));
        $this->assign('pay_status',C('PAY_STATUS'));
        $this->assign('shipping_status',C('SHIPPING_STATUS'));

        $this->display();
    }

    /*
     *Ajax首页
     */
    public function ajaxPintOrder(){
        $orderLogic = new OrderLogic();

        $timegap = I('timegap');
        if($timegap){
            $gap = explode('-', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        // 搜索条件
        $condition = array();
        $condition['store_id'] = STORE_ID;
        $pint_status = I('pint_status',3);
        if($pint_status != 3){
            $pint_id_arr = M('pint')->where('pint_status = '.$pint_status)->getField('pint_id',true);
            if($pint_id_arr){
                $condition['order_prom_id'] = array('in',$pint_id_arr);
            }else{
                $this->display();
                die;
            }
        }
        I('consignee') ? $condition['consignee'] = trim(I('consignee')) : false;
        if($begin && $end){
            $condition['add_time'] = array('between',"$begin,$end");
        }
        $store_name = I('store_name','','trim');
        if($store_name)
        {
            $store_id_arr = M('store')->where("store_name like '%$store_name%'")->getField('store_id',true);
            if($store_id_arr)
            {
                $condition['store_id'] = array('in',$store_id_arr);
            }
        }
        $condition['order_prom_type'] = '101';
        I('order_sn') ? $condition['order_sn'] = trim(I('order_sn')) : false;
        I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
        I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
        I('pay_code') != '' ? $condition['pay_code'] = I('pay_code') : false;
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;
        $sort_order = I('order_by','DESC').' '.I('sort');
        $count = M('order')->where($condition)->where(" !(pay_code!='cod' and pay_status = 0)")->count();
        $Page  = new AjaxPage($count,20);
        //  搜索条件下 分页赋值
      //  foreach($condition as $key=>$val) {
          //  $Page->parameter[$key]   =  urlencode($val);
      //  }
        $show = $Page->show();
        //获取订单列表
        $orderList = $res = M('order')->where($condition)->where(" !(pay_code!='cod' and pay_status = 0) ")->limit($Page->firstRow.','.$Page->listRows)->order($sort_order)->select();
        foreach($orderList as $key=>$value){
            
            $orderList[$key]["pay_name"]=M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>$value['pay_code']))->getField('name'); 
        }
        $store_list = M('store')->getField('store_id,store_name');        
        $this->assign('store_list',$store_list);       
        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出

        $this->assign('order_status',C('ORDER_STATUS'));
        $this->assign('pay_status',C('PAY_STATUS'));
        $this->assign('shipping_status',C('SHIPPING_STATUS'));
        
        $this->display();
    }
    
    public function export_order()
    {
        //搜索条件        
        $where = "where store_id =".STORE_ID." and is_pint=1 ";
        $consignee = I('consignee');
        if($consignee){
            $where .= " AND consignee like '%$consignee%' ";
        }
        $order_sn =  I('order_sn');
        if($order_sn){
            $where .= " AND order_sn = '$order_sn' ";
        }
        if(I('order_status')){
            $where .= " AND order_status = ".I('order_status');
        }
        
        $timegap = I('timegap');
        if($timegap){
            $gap = explode('-', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
            $where .= " AND add_time>$begin and add_time<$end";
        }
    $region = M('region')->getField('id,name');
                
    $sql = "select *,FROM_UNIXTIME(add_time,'%Y-%m-%d') as create_time from __PREFIX__order $where order by order_id";
        $orderList = D()->query($sql);   
        $strTable ='<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">订单编号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">日期</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货人</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货地址</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">电话</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">实际支付</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">支付方式</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">支付状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">发货状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">商品信息</td>';
        $strTable .= '</tr>';
        
        foreach($orderList as $k=>$val){
            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_sn'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['create_time'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'."{$region[$val['province']]},{$region[$val['city']]},{$region[$val['district']]},{$region[$val['twon']]}{$val['consignee']}".' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['address'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['mobile'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['goods_price'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['order_amount'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['pay_name'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$this->pay_status[$val['pay_status']].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$this->shipping_status[$val['shipping_status']].'</td>';    
            $orderGoods = D('order_goods')->where('order_id='.$val['order_id'])->select();
            $strGoods="";
            foreach($orderGoods as $goods){
                $strGoods .= "商品编号：".$goods['goods_sn']." 商品名称：".$goods['goods_name'];
                if ($goods['spec_key_name'] != '') $strGoods .= " 规格：".$goods['spec_key_name'];
                $strGoods .= "<br />";
            }
            unset($orderGoods);
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$strGoods.' </td>';
            $strTable .= '</tr>';
        }
        $strTable .='</table>';
        unset($orderList);
        downloadExcel($strTable,'order');
        exit();
    }
}